package activity

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"mall/common/ctxdatax"
	"mall/common/globalkey"
	"mall/service/backend/common/utils/pointy"
	"mall/service/forum/api/internal/logic/promotion/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/promotion/rpc/promotionclient"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetPromotionActivityListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPromotionActivityListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromotionActivityListLogic {
	return &GetPromotionActivityListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPromotionActivityListLogic) GetPromotionActivityList(
	req *types.PromotionActivityListReq,
) (resp *types.PromotionActivityListInfo, err error) {
	userId := ctxdatax.GetUserId(l.ctx)
	// if userId == 0 {
	// 	return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	// }

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	var preload string =
		"activity:Id,Name,Desc,Members,Type,Mutex,Scope,TimesLimit,StartedAt,EndedAt"
	var eagerLoad string = "activity:logTotal"
	var filters []string
	filters = append(filters, "Status,equalTo:" + strconv.FormatInt(int64(globalkey.StatusStarted), 10))
	// if filterMap := parse.ParseFilter(req.Filter); filterMap != nil {
	// 	for key, val := range filterMap {
	// 		switch key {
	// 		case "type":
	// 			filters = append(filters, "Type,equalTo:" + val)
	// 		}
	// 	}
	// }
	if req.ActivityType != nil {
		filters = append(filters, "Type,equalTo:" + strconv.FormatInt(int64(*req.ActivityType), 10))
	}

	res, err := l.svcCtx.PromotionRpc.GetActivityList(l.ctx, &promotionclient.BaseListReq{
		Offset:     uint32((page-1)*pageSize),
		Limit:      uint32(pageSize),
		Preload:    &preload,
		EagerLoad:  &eagerLoad,
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     req.Sorter,
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	logrus.Info(fmt.Sprintf("GetPromotionActivityList: %+v", res))

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.PromotionActivityListInfo{
		BaseListInfo: types.BaseListInfo{
			Current:         page,
			PageSize:        pageSize,
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	for _, v := range res.List {
		var timeRange []string
		if v.StartedAt != nil && v.EndedAt != nil {
			timeRange = []string{*v.StartedAt, *v.EndedAt}
		}

		var activityTypeText string = util.GetActivityTypeText(v.ActivityType)
		var mutexTypeText string = util.GetMutexTypeText(v.MutexType)
		var scopeTypeText string = util.GetScopeTypeText(v.ScopeType)
		var groupModeText string = util.GetGroupModeText(v.GroupMode)
		var groupTypeText string = util.GetGroupTypeText(v.GroupType)

		resp.List = append(resp.List, &types.PromotionActivityInfo{
			Id:                    v.Id,
			Name:                  v.Name,
			Description:           v.Description,
			MemberRestriction:     v.MemberRestriction,
			ActivityType:          v.ActivityType,
			ActivityTypeText:      &activityTypeText,
			MutexType:             v.MutexType,
			MutexTypeText:         &mutexTypeText,
			ScopeType:             v.ScopeType,
			ScopeTypeText:         &scopeTypeText,
			TimesLimit:            v.TimesLimit,
			GroupMode:             v.GroupMode,
			GroupModeText:         &groupModeText,
			GroupType:             v.GroupType,
			GroupTypeText:         &groupTypeText,
			SeckillLimit:          v.SeckillLimit,
			SeckillCancelDuration: v.SeckillCancelDuration,
			SeckillNotifyDuration: v.SeckillNotifyDuration,
			PackageType:           v.PackageType,
			PackagePicId:          v.PackagePicId,
			PackagePicUrl:         v.PackagePicUrl,
			TimeRange:             timeRange,
			Status:                v.Status,
			LogTotal:              v.LogTotal,
		})
	}

	return resp, nil
}
